package com.jrx.anytxn.investor.service.impl;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.BeanUtils;
import com.jrx.anytxn.investor.constant.TransBizConstant;
import com.jrx.anytxn.investor.entity.AmAccountMainInvestorInfo;
import com.jrx.anytxn.investor.entity.AmLoanMainInvestorInfo;
import com.jrx.anytxn.investor.entity.TlPaymentAllocationInvestorLog;
import com.jrx.anytxn.investor.entity.TlPaymentInvestorLog;
import com.jrx.anytxn.investor.service.IInvestorAccountService;
import com.jrx.anytxn.investor.service.IInvestorTlPaymentAllocationLogService;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.transaction.service.ITlPaymentAllocationLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @program: anytxn-cf-transaction
 * @description:
 * @author: xiaoyu.jing
 * @date: 2020-05-22 16:40
 **/
@Service
public class InvestorTlPaymentAllocationLogServiceImpl implements IInvestorTlPaymentAllocationLogService {

    private static final Logger logger = LoggerFactory.getLogger(InvestorTlPaymentAllocationLogServiceImpl.class);

    @Autowired
    private IInvestorAccountService accountService;
    @Autowired
    private ISegmentService segmentService;
    @Autowired
    private ITlPaymentAllocationLogService tlPaymentAllocationLogService;

    @Override
    public TlPaymentAllocationInvestorLog buildTlPaymentAllocationInvestorLog(TlPaymentInvestorLog paymentLog, AmLoanMainInvestorInfo loanMainInvestorInfo, Date bussinessDate) throws TxnBizException {
        TlPaymentAllocationInvestorLog paymentAllocationInvestorLog = new TlPaymentAllocationInvestorLog();
        BeanMapping.copy(loanMainInvestorInfo, paymentAllocationInvestorLog);
        try {
            paymentAllocationInvestorLog.setId(segmentService.getId(TransBizConstant.TL_PAYMENT_ALLOCATION_INVESTOR_LOG_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        //08会计状态，应计/非应计取默认参数，
        paymentAllocationInvestorLog.setInvestorId("");
        paymentAllocationInvestorLog.setInvestorLoanId("");
        paymentAllocationInvestorLog.setLoanId(paymentLog.getLoanId());
        paymentAllocationInvestorLog.setAccountingPhase(TransBizConstant.ACCOUNTING_PHASE_0);
        paymentAllocationInvestorLog.setNonAccrualsFlag(TransBizConstant.NON_ACCRUALS_FLA_0);
        paymentAllocationInvestorLog.setAccountId(accountService.getAccountId(TransBizConstant.PAYMENT_ALLOCATION_TYPE_08,
                loanMainInvestorInfo.getTenantId(),loanMainInvestorInfo.getCustomerId()));
        paymentAllocationInvestorLog.setAccountType(TransBizConstant.PAYMENT_ALLOCATION_TYPE_08);
        paymentAllocationInvestorLog.setTxnCode(TransBizConstant.TXN_CODE_PAYMENT_DETAIL);
        paymentAllocationInvestorLog.setPostingAmount(paymentLog.getTotalAmount());
        paymentAllocationInvestorLog.setSeqNo(paymentLog.getSeqNo());
        paymentAllocationInvestorLog.setPaymentType(paymentLog.getPaymentType());
        paymentAllocationInvestorLog.setPostingDate(bussinessDate);
        paymentAllocationInvestorLog.setUpdateBy(TransBizConstant.SYS_OPRATE);
        paymentAllocationInvestorLog.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
        //添加代偿回购判断
        if(TransBizConstant.REPAYMENT_TYPE_CMPS.equals(paymentLog.getPaymentType())||
                TransBizConstant.REPAYMENT_TYPE_CRT.equals(paymentLog.getPaymentType())){
            paymentAllocationInvestorLog.setCompensatoryFlag(TransBizConstant.COMPENSATORY_FLAG_1);
        }
        paymentAllocationInvestorLog.setCreateTime(null);
        paymentAllocationInvestorLog.setUpdateTime(null);
        paymentAllocationInvestorLog.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
        logger.info("生成08还款交易账户paymentAllocationInvestorLog:{}", BeanUtils.toMap(paymentAllocationInvestorLog));
        return paymentAllocationInvestorLog;
    }

    /**
     * 生成09子还款交易账户
     *
     * @param totalAllocationLog
     * @param acct
     * @return
     */
    @Override
    public TlPaymentAllocationInvestorLog buildTlPaymentAllocationLog(TlPaymentAllocationInvestorLog totalAllocationLog, AmAccountMainInvestorInfo acct, BigDecimal realPaymentAmnt)throws TxnBizException {
        TlPaymentAllocationInvestorLog paymentAllocationLog = new TlPaymentAllocationInvestorLog();
        BeanMapping.copy(acct, paymentAllocationLog);
        try {
            paymentAllocationLog.setId(segmentService.getId(TransBizConstant.TL_PAYMENT_ALLOCATION_INVESTOR_LOG_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        paymentAllocationLog.setAccountId(accountService.getAccountId(TransBizConstant.PAYMENT_ALLOCATION_TYPE_09,
                acct.getTenantId(),acct.getCustomerId()));
        paymentAllocationLog.setPaymentType(totalAllocationLog.getPaymentType());
        paymentAllocationLog.setAccountType(TransBizConstant.PAYMENT_ALLOCATION_TYPE_09);
        String txnCode = tlPaymentAllocationLogService.getPaymentDetailTxnAccountTxnCode(acct.getTxnCode(), totalAllocationLog.getTxnCode() ,
                totalAllocationLog.getPaymentType(),acct.getChargeoffFlag(),acct.getAccountType());
        paymentAllocationLog.setTxnCode(txnCode);
        paymentAllocationLog.setSeqNo(totalAllocationLog.getSeqNo());
        paymentAllocationLog.setPostingDate(totalAllocationLog.getPostingDate());
        paymentAllocationLog.setPostingAmount(realPaymentAmnt);
        paymentAllocationLog.setOriginalAccountId(totalAllocationLog.getAccountId());
        paymentAllocationLog.setConnectAccountType(acct.getAccountType());
        paymentAllocationLog.setConnectAccountId(acct.getAccountId());
        //税金大于0
        if (acct.getTaxAmt()!=null && acct.getTaxAmt().compareTo(BigDecimal.ZERO)>0){
            //核销时税金登记  表外还款时登记税金
            if (TransBizConstant.CHARGOFF_FLAG_1.equals(acct.getChargeoffFlag())
                    || TransBizConstant.NON_ACCRUALS_FLA_1.equals(acct.getNonAccrualsFlag())) {
                //因为存在部分逾期还款 所以采用 每次登记税金 = （本次还款额+已还款额）/总应还额 * 总税金 的计算法则，保证多次逾期还款后，登记税金 = 原交易账户税
                BigDecimal afterPayTaxAmt = acct.getRepayAmount().add(realPaymentAmnt).multiply(acct.getTaxAmt()).divide(acct.getPostingAmount(), 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal beforeTaxAmt = acct.getRepayAmount().multiply(acct.getTaxAmt()).divide(acct.getPostingAmount(), 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal taxAmt = afterPayTaxAmt.subtract(beforeTaxAmt).setScale(2, BigDecimal.ROUND_HALF_UP);
                paymentAllocationLog.setTaxAmt(taxAmt);
            }
        }else{
            paymentAllocationLog.setTaxAmt(BigDecimal.ZERO);
        }
        paymentAllocationLog.setLiabilityFlag(acct.getLiabilityFlag());
        paymentAllocationLog.setUpdateBy(TransBizConstant.SYS_OPRATE);
        paymentAllocationLog.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
        if(TransBizConstant.REPAYMENT_TYPE_CMPS.equals(totalAllocationLog.getPaymentType())){
            paymentAllocationLog.setCompensatoryFlag(TransBizConstant.COMPENSATORY_FLAG_1);
        }
        paymentAllocationLog.setCreateTime(null);
        paymentAllocationLog.setUpdateTime(null);
        paymentAllocationLog.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
        logger.info("生成09还款交易账户paymentAllocationLog:{}", BeanUtils.toMap(paymentAllocationLog));
        return paymentAllocationLog;
    }
}
